package com.numberone.iotplatform.controller;


import com.numberone.iotplatform.dto.BatchImportRequestDTO;
import com.numberone.iotplatform.entity.DiscoveredDevice;
import com.numberone.iotplatform.repository.DiscoveredDeviceRepository;
import com.numberone.iotplatform.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;

/**
 * 处理与设备发现池相关的API请求。
 */
@RestController
@RequestMapping("/discovered-devices")
@PreAuthorize("hasRole('ADMIN')") // 只有管理员可以访问发现池
public class DiscoveredDeviceController {

    @Autowired
    private DiscoveredDeviceRepository discoveredDeviceRepository; // 注入真实 Repository

    /**
     * 【核心改造】从真实数据库中分页查询发现池中的设备列表。
     */
    @GetMapping
    public ResponseEntity<Page<DiscoveredDevice>> getDiscoveredDevices(Pageable pageable) {
        // 直接调用 repository 的 findAll 方法进行分页查询
        Page<DiscoveredDevice> devicePage = discoveredDeviceRepository.findAll(pageable);
        return ResponseEntity.ok(devicePage);
    }

    @Autowired
    private DeviceService deviceService; // 注入 DeviceService

    //  批量导入接口
    @PostMapping("/batch-import")
    public ResponseEntity<Void> batchImport(@Valid @RequestBody BatchImportRequestDTO request) {
        deviceService.batchImportDevices(request);
        return ResponseEntity.ok().build();
    }
}